package user

import (
	"context"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"time"
)

type CommonUserBindRepository struct {
}

func NewCommonUserBindRepository() CommonUserBindRepoIface {
	return &CommonUserBindRepository{}
}

//获取详情
func (r *CommonUserBindRepository) GetInfo(ctx context.Context, condition map[string]interface{}) (*CommonUserBind, error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserBind := &CommonUserBind{}
	err := db.Table(commonUserBind.TableName()).Where(condition).Where("is_deleted = 0").First(&commonUserBind).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserBind, nil
}

//获取列表数据
func (r *CommonUserBindRepository) GetList(ctx context.Context, condition map[string]interface{}, page, pagesize int, orderBy string) (int64, []*CommonUserBind, error) {
	db := stark.MySQLConn.Get(ctx)

	commonUserBindList := []*CommonUserBind{}
	var count int64 = 0
	if page < 1 {
		page = 1
	}
	if pagesize < 1 {
		pagesize = 10
	}
	offset := (page - 1) * pagesize

	query := db.Where(condition)
	err := query.Count(&count).Error
	if err != nil {
		return 0, nil, err
	}
	query = query.Offset(offset).Limit(pagesize).
		Find(&commonUserBindList)
	if orderBy != "" {
		query = query.Order(orderBy)
	}
	err = query.Error
	if err != nil {
		return 0, nil, err
	}
	return count, commonUserBindList, nil
}

//通过租户用户id查询绑定表mpopenid列表
func (r *CommonUserBindRepository) GetDistinctMpOpenidsByCommonUserId(ctx context.Context, commonUserId string) ([]string, error) {
	db := stark.MySQLConn.Get(ctx)
	var commonUserBind []*CommonUserBind
	condition := make(map[string]interface{})
	condition["tenant_user_uid"] = commonUserId
	condition["tenant_code"] = ""

	err := db.Distinct("mp_openid").
		Where("common_user_data_uid = ? AND is_deleted = ?", commonUserId, 0).
		Find(&commonUserBind).Limit(1000).Error
	if err != nil {
		return nil, err
	}
	var mpOpenids []string
	for _, v := range commonUserBind {
		mpOpenids = append(mpOpenids, v.MpOpenid)
	}
	return mpOpenids, nil
}


// 绑定mp openid 列表
func (r *CommonUserBindRepository) BindMpOpenids(ctx context.Context, commonUserDataUid string, tenantUserUid string, mpOpenids []string) error {
	db := stark.MySQLConn.Get(ctx)
	var commonUserBinds []*CommonUserBind
	for _, mpOpenid := range mpOpenids {
		commonUserBinds = append(commonUserBinds, &CommonUserBind{
			Uid: uuid.New().String(),
			CommonUserDataUid: commonUserDataUid,
			TenantUserUid: tenantUserUid,
			MpOpenid: mpOpenid,
			CreatedTime: time.Now(),
		})
	}
	err := db.Create(commonUserBinds).Error
	if err != nil {
		return err
	}
	return nil
}

// 通过手机号获取最新openid绑定关系
func (r *CommonUserBindRepository) GetLastBindByMobile(ctx context.Context, mobile string, excludeCommonUserId string) (commonUserBind *CommonUserBind, err error) {
	db := stark.MySQLConn.Get(ctx)
	commonUserBind = &CommonUserBind{}
	err = db.Model(&CommonUserBind{}).
		Select("common_user_bind.*").
		Joins("LEFT JOIN common_user_data ON common_user_bind.common_user_data_uid = common_user_data.uid").
		Where("common_user_data.mobile_phone = ? AND common_user_data.uid != ? and common_user_data.is_deleted = 0 and common_user_bind.is_deleted = 0 and common_user_bind.mp_openid != '' ", mobile, excludeCommonUserId).
		Order("common_user_bind.created_time DESC").
		Limit(1).
		Find(&commonUserBind).
		Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return commonUserBind, nil
}

//更新数据
func (r *CommonUserBindRepository) Update(ctx context.Context, data, condition map[string]interface{}) (bool, error) {
	db := stark.MySQLConn.Get(ctx)

	err := db.Model(&CommonUserBind{}).Where(condition).Updates(data).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

//插入数据
func (r *CommonUserBindRepository) Insert(ctx context.Context, commonUserBind *CommonUserBind) (bool, error) {
	db := stark.MySQLConn.Get(ctx)

	err := db.Save(commonUserBind).Error
	if err != nil {
		return false, err
	}

	return true, nil
}

//插入绑定错误记录
func (r *CommonUserBindRepository) InsertFailRecord(ctx context.Context, commonUserBindFailRecord *CommonUserBindFailRecord) (bool, error) {
	db := stark.MySQLConn.Get(ctx)
	err := db.Save(commonUserBindFailRecord).Error
	if err != nil {
		return false, err
	}
	return true, nil
}

//逻辑删除数据
func (r *CommonUserBindRepository) Delete(ctx context.Context, condition map[string]interface{}) (bool, error) {
	updateData := map[string]interface{}{}
	updateData["is_deleted"] = 1
	updateData["modified_time"] = time.Now()
	db := stark.MySQLConn.Get(ctx)

	err := db.Model(&CommonUserBind{}).Where(condition).Updates(updateData).Error
	if err != nil {
		return false, err
	}
	return true, nil
}
